package se.sweco.dataservice.impl;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import se.sweco.dataservice.TaxDataService;
import se.sweco.dataservice.TinfoWSException;
import se.sweco.dataservice.TrafficData;
import se.sweco.dataservice.TrafficDataService;

public class TinfoServiceImpl implements TaxDataService, TrafficDataService {
	private static final String DEFAULT_WS_LOCATION = "http://localhost";
	private static final String PATH_TAX = "/tax";
	private static final String PATH_TRAFFIC = "/traffic";
	private static final String DEFAULT_IO_ERROR = "Error in server communication.";

	private XMLReader parser;
	
	public TinfoServiceImpl() {
		try {
			parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
		} catch (SAXException e) {
			System.err.println(e.getMessage());
		}
	}
	private void fetchData(String uri, XMLDataHandler handler) throws TinfoWSException {
		HttpURLConnection conn = null;
		
		try {
			URL url = new URL(uri);
			conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.connect();

			parser.setContentHandler(handler);
			InputSource source = new InputSource(conn.getInputStream());
			parser.parse(source);
		} catch (MalformedURLException e) {
			/* /Ignore */
		} catch (IOException e) {
			/* Ignore and throw default */
			throw new TinfoWSException(DEFAULT_IO_ERROR);
		} catch (SAXException e) {
			/* /Ignore */
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}

		if (handler.hasError()) {
			throw new TinfoWSException(handler.getError());
		}
	}
	
	@Override
	public double getTaxRate(double lat, double lon) throws TinfoWSException {
		XMLDataHandler handler = new XMLDataHandler();
		String url = getHost() + PATH_TAX + "?lat=" + lat + "&lon=" + lon;
		fetchData(url, handler);
		return handler.getTaxRate();
	}

	@Override
	public List<TrafficData> getTrafficData(double lat, double lon, double radius) throws TinfoWSException {
		XMLDataHandler handler = new XMLDataHandler();
		String url = getHost() + PATH_TRAFFIC + "?lat=" + lat + "&lon=" + lon + "&r=" + radius;
		fetchData(url, handler);
		return handler.getTrafficData();
	}

	private String getHost() {
		String host = System.getProperty("tinfo.ws.host");
		if (host == null || host.isEmpty()) {
			return DEFAULT_WS_LOCATION;
		}
		return host;
	}

}
